#include <SDL/SDL.h>
#include <iostream>
#include <list>
#include <vector>
#include <string>

#include "config.h"
#include "game.h"
#include "player.h"
#include "field.h"

void Slock(SDL_Surface *screen){
	if ( SDL_MUSTLOCK(screen) ){
		if ( SDL_LockSurface(screen) < 0 ){
			return;
		}
	}
}

void Sulock(SDL_Surface *screen){
	if ( SDL_MUSTLOCK(screen) ){
		SDL_UnlockSurface(screen);
	}
}

int main (int argc, char ** argv) {
	int err = SDL_Init(SDL_INIT_EVERYTHING);
	if (err < 0) {
		std::cout << "Failed to init SDL" << std::endl;
		return 1;
	}
	SDL_Surface * Screen;
	Screen = SDL_SetVideoMode(640, 480, 32, SDL_HWSURFACE | SDL_DOUBLEBUF);
	if (!Screen) {
		std::cout << "Faileed to init video" << std::endl;
		SDL_Quit();
		return 1;
	}

	Game game;
	game.LoadConfig(DEFAULT_XML_CONFIG);
	game.LoadMap(DEFAULT_MAP);

	unsigned time;

	bool exit = false;
	while (!exit) {
		time = SDL_GetTicks();
		game.GetTickies().HandleTick(time);
		game.GetField().HandleTick(time);
		Slock(Screen);
			game.Draw(Screen);
			game.GetTickies().Draw(Screen, time);
		SDL_Flip(Screen);
		Sulock(Screen);
		SDL_Event event;
		while ( SDL_PollEvent(&event) ) {
			if ( event.type == SDL_QUIT ) { exit = true; }
			if ( event.type == SDL_KEYDOWN ) {
				if ( event.key.keysym.sym == SDLK_ESCAPE ){
					exit = true;
				}
				if ( event.key.keysym.sym == SDLK_UP){
					game.GetPlayer().SetDirection(UP);
				}
				if ( event.key.keysym.sym == SDLK_DOWN){
					game.GetPlayer().SetDirection(DOWN);
				}
				if ( event.key.keysym.sym == SDLK_LEFT){
					game.GetPlayer().SetDirection(LEFT);
				}
				if ( event.key.keysym.sym == SDLK_RIGHT){
					game.GetPlayer().SetDirection(RIGHT);
				}
				if ( event.key.keysym.sym == SDLK_SPACE){
					game.GetPlayer().SetDirection(STOP);
				}
				if ( event.key.keysym.sym == 'a'){
					game.GetObjTbl()['z'].bombExploding = false;
					game.GetObjTbl()['z'].bombTime = SDL_GetTicks();
					game.GetField()(game.GetPlayer().x, game.GetPlayer().y) = game.GetObjTbl()['z'];
				}
			}
		}
	}
	
	SDL_Quit();
	return 0;
}
